package web.controller;

import java.io.IOException;
import java.net.MalformedURLException;
import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import entities.Status;
import service.authentification.Contributor;
import service.configuration.IConfiguration;
import service.normalization.INormalizer;
import service.sheetmanager.ISheetManager;
import service.sheetmanager.SheetNotFoundException;
import web.form.SheetView;

/**
 * <b>UpdateController  </b>
 * <p>UpdateController controle les requêtes pour le module de saisie.</p>
 * 
 */
@Controller
public class UpdateController {
	
	/**
     * Repr&eacute;sente le service de gestion de fiches
     */
	@Resource
	ISheetManager sheetManager;
	
	/**
     * Repr&eacute;sente le service de normalisation
     */
	@Resource
	INormalizer normalizer;
	
	/**
     * Repr&eacute;sente le service de configuration
     */
	@Resource
	IConfiguration config;

	
	/**
     * Controlleur qui renvoi la page de saisie
     */
	@RequestMapping(value = "/update.htm", method = RequestMethod.GET)
	public String showform(HttpSession session, ModelMap model,
			@RequestParam(value = "code", required = false) String code,
			@RequestParam(value = "type", required = false) String type)
			throws ServletException, IOException {
		
		SheetView sheetView = sheetManager.findSheet(code, type);
		if (sheetView == null) {
			return "error/notFound";
		}
		
		Contributor user = (Contributor) session.getAttribute("user");
		if((user == null) || 
			!sheetManager.personIsAllowedToModifySheet(user.getCode(), code)) {
			URIParser uri = new URIParser("sheet.htm");
			uri.setParameter("code",code);
			uri.setParameter("type",type);
			uri.setParameter("login", "open");
			
			return "redirect:"+uri.getUrl();
		}

		

		model.addAttribute("sheetView", sheetView);
		return "update";
	}

	/**
     * Controlleur qui recoi les modification effectué par un utilisateur sur une fiche
     */
	@RequestMapping(value = "/update.htm", method = RequestMethod.POST)
	public String onSubmitUpdate(HttpSession session,
			@ModelAttribute("sheetView") SheetView sheetView,
			BindingResult result, ModelMap model) throws JSONException, MalformedURLException {
		Contributor user = (Contributor)session.getAttribute("user");
		Status status;
		if((user!=null)&&(sheetManager.personIsAllowedToModifySheet(user.getCode(), sheetView.getCode()))){
			try {
				status=sheetManager.updateSheet(sheetView, result);
			} catch (SheetNotFoundException e) {
				return "error/notFound";
			}	
			
		}else{
			URIParser uri = new URIParser("sheet.htm");
			uri.setParameter("code",sheetView.getCode());
			uri.setParameter("type",sheetView.getType());
			uri.setParameter("login", "open");
			return "redirect:"+uri.getUrl();
		}
		if(status!=null)
			if(status.equals(Status.Valid)){
				model.addAttribute("status", "valid");
			}else{
				if(status.equals(Status.SoftError)){
					model.addAttribute("status", "soft");
				}else{
					model.addAttribute("status", "hard");
				}
			}
		
		return "update";
	}

	/**
     * Controlleur qui normalise des champs de type paragraphe via le service de normalisation
     */
	@RequestMapping(value = "/normalize.htm", method = RequestMethod.POST)
	public String handleRequestJson(HttpSession session, ModelMap model,
			@RequestParam(value="text", required=false) String uriText)
					throws JSONException, InterruptedException, MalformedURLException  {
		System.out.println(uriText);
		JSONObject jsonText = new JSONObject();
		System.out.println(normalizer.normalizeText(uriText));
		jsonText.put("text", normalizer.normalizeText(uriText));
		
		model.addAttribute("jsonArray", jsonText);
		return "json";
	}	
	
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		binder.setAutoGrowNestedPaths(false);
	}
}
